package br.edu.sistemaacademico.observer;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class ValidaEspecial implements Observer{

    public ValidaEspecial() { }    
    
    public void remove(final Observavel o){
           SwingUtilities.invokeLater(new Runnable() {
           public void run() {
            Document d = o.getDocument();
                    try {
                   	 if(o.getDocument().getLength()>=1)
                        d.remove(o.getDocument().getLength()-1,1);
                    } catch (BadLocationException ex) {
                        Logger.getLogger(ValidaTelefone.class.getName()).log(Level.SEVERE, null, ex);
                    }
             o.setDocument(d);
            }
        });
    }

    public void update(final Observavel o, Object arg) {
        try {
        	String document =  o.getDocument().getText(0, o.getDocument().getLength());
            char character; 
            Pattern patter = Pattern.compile("[a-zA-Z_0-9\\s]");
            if(o.getDocument().getLength()<1)
            character = o.getDocument().getText(0, 1).charAt(0);
            else
            character = o.getDocument().getText(0, o.getDocument().getLength()).charAt(o.getDocument().getLength()-1);
            Matcher matcher = patter.matcher(String.valueOf(character));
            if(!matcher.find()||o.getDocument().getLength()==30)
                    remove(o);
        } catch (BadLocationException ex) {
            Logger.getLogger(ValidaTelefone.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
